package lichtruong.bk.cse;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class Report extends Activity implements OnMapClickListener {

	ProgressDialog pDialog;
	// map
	int leveluser;
	GoogleMap googleMap;
	LatLng POINT_SHOW, POINT_CURRENT;
	Marker poinCurrent, poinShow;
	static double latitude, longitude;
	// dialog
	private final static int GPSOFF_DIALOG = 0;
	private final static int CHOOSE_TYPE_REPORT = 1;
	int type_report = 0;

	@SuppressWarnings("deprecation")
	// auto add when click show dialog
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map1);
		// google map ===================================
		googleMap = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.map)).getMap();
		// ===============================================
		if (!check_locationCurrent()) {
			// Internet
			Report.this.showDialog(CHOOSE_TYPE_REPORT);
			googleMap.setOnMapClickListener(this);
		} else {
			// GPS
			new GetPointReport().execute();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		super.onOptionsItemSelected(item);
		optionSelect();
		return true;
	}
	
	private void optionSelect(){
		String login;
		Database getlevel = new Database(Report.this);
		getlevel.open();
		if(Integer.parseInt(getlevel.getData_USER().level) == 0){
			login = "                 Đăng Nhập     ";
			leveluser = Integer.parseInt(getlevel.getData_USER().level);
		}else{
			login = "                 Đăng Xuất     ";
			leveluser = Integer.parseInt(getlevel.getData_USER().level);
		}
		getlevel.close();
		CharSequence[] items = {"                   Đăng Ký ", login,"               Xem Tự Động   ", "     Xem Các Điểm Tắc Đường  "};
		new AlertDialog.Builder(this)
		.setTitle("   Danh Sách Lựa Chọn  ")
		.setItems(items, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(which == 0){
					Intent register = new Intent(Report.this, Register.class);
					startActivity(register);
				}else if(which == 1){
					if(leveluser == 0){
						Intent login = new Intent(Report.this, Login.class);
						login.putExtra("back", "2");
						startActivity(login);
					}else{
						Database updateLevel = new Database(Report.this);
						updateLevel.open(); updateLevel.updateLevelUser("0"); updateLevel.close();
						Toast.makeText(getBaseContext(), "Đăng Xuất Thành Công", Toast.LENGTH_SHORT).show();
						Intent menu = new Intent(Report.this, menu.class);
						startActivity(menu);
					}
				}else if(which == 2){
					Intent autoget = new Intent(Report.this, AuToGet.class);
					startActivity(autoget);
				}else{
					Intent reported = new Intent(Report.this, GetDataReported.class);
					startActivity(reported);
				}
			}
		}).show();
		//.setMessage(message)
	}
	
	@Override // - OK
	public void onMapClick(LatLng point) {
		// TODO Auto-generated method stub
		latitude = point.latitude;
		longitude = point.longitude;
		POINT_CURRENT = new LatLng(latitude, longitude);
		new GetPointReport().execute();
	}
	
	// check GPS on or off - OK
	public boolean check_locationCurrent() {
		menu locationCurrent = new menu();
		double[] latlngCurrent = locationCurrent.locationCurrent();
		latitude = latlngCurrent[0];
		longitude = latlngCurrent[1];
		POINT_CURRENT = new LatLng(latitude, longitude);
		if (latitude == 10.776126655419617 && longitude == 106.64446815587598) {
			return false;
		}
		type_report = 0;
		return true;
	}

	// Dialog -  OK
	@Override
	protected Dialog onCreateDialog(int id) {

		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case GPSOFF_DIALOG:

			builder.setMessage(
					"Bạn Phải Bật GPS Trước Khi Thực Hiện Chức Năng Báo Cáo Tắc Đường")
					.setPositiveButton("Tiếp Tục",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent menu = new Intent(Report.this, menu.class);
									startActivity(menu);
								}
							})
					.setNegativeButton("Hủy",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent menu = new Intent(Report.this, menu.class);
									startActivity(menu);
								}
							}).setCancelable(false);
			dialog = builder.create();
			break;

		case CHOOSE_TYPE_REPORT:

			builder.setTitle("  Bạn Hãy Chọn Kiểu Báo Cáo  ")
					.setPositiveButton("GPS",
							new DialogInterface.OnClickListener() {

								@SuppressWarnings("deprecation")
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Report.this.showDialog(GPSOFF_DIALOG);
								}
							})
					.setNegativeButton("Internet",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {

									googleMap.moveCamera(CameraUpdateFactory
											.newLatLngZoom(POINT_CURRENT, 15));
									googleMap.animateCamera(
											CameraUpdateFactory.zoomTo(13),
											2000, null);
									type_report = 1;
									dialog.cancel();
								}
							}).setCancelable(false);
			dialog = builder.create();
			break;
		}
		return dialog;
	}

	class GetPointReport extends AsyncTask<String, String, String> {
		// get data
		CharSequence items[];
		CharSequence[] id_check;
		JSONArray infomations_point_report;
		JSONParser JsonParser = new JSONParser();
		ArrayList<PNR> informationall = new ArrayList<PNR>();
		private static final String URL_GETINFO = "http://lichcse.hol.es/findpointnear.php";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Report.this);
			pDialog.setMessage("Please wait report ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {
			// Check for success tag
			int success;
			try {
				// Building Parameters
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("lat", String
						.valueOf(latitude)));
				params.add(new BasicNameValuePair("lng", String
						.valueOf(longitude)));
				// Posting user data to script
				JSONObject json = JsonParser.makeHttpRequest(URL_GETINFO,
						"POST", params);

				success = json.getInt("success"); // error

				if (success == 1) {

					infomations_point_report = json
							.getJSONArray("point_report");

					for (int i = 0; i < infomations_point_report.length(); i++) {
						JSONObject l = infomations_point_report
								.getJSONObject(i);
						PNR point = new PNR();
						point.id = l.getString("id");
						point.info = l.getString("info");
						point.lat = l.getString("lat");
						point.lng = l.getString("lng");
						informationall.add(point);
					}
				} else {

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog once product deleted
			pDialog.dismiss();
			if (informationall.size() > 0) {
				reportDialog();
			} else {
				findNull();
			}
		}

		// show dialog report if number point > 0
		public void reportDialog() {
			items = new String[informationall.size()];
			id_check = new String[informationall.size()];
			for (int i = 0; i < informationall.size(); i++) {
				id_check[i] = "";
				items[i] = informationall.get(i).info;
			}
			AlertDialog.Builder builder = new AlertDialog.Builder(Report.this);
			builder.setTitle("Chọn Điểm Đang Tắc Đường")
					.setMultiChoiceItems(items, null,
							new DialogInterface.OnMultiChoiceClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which, boolean isChecked) {
									// TODO Auto-generated method stub
									if (isChecked) {
										Toast.makeText(
												getBaseContext(),
												"Bạn Vừa Chọn : "
														+ items[which]
														+ " - Là Điểm Tắc Đường",
												Toast.LENGTH_SHORT).show();
										id_check[which] = "1";
									} else {
										Toast.makeText(
												getBaseContext(),
												"Bạn Vừa Bỏ Chọn : "
														+ items[which]
														+ " - Là Điểm Tắc Đường",
												Toast.LENGTH_SHORT).show();
										id_check[which] = "";
									}
								}
							})
					.setPositiveButton("Báo Tắc Đường",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									// code report
									int count_isnull = 0;
									for (int i = 0; i < informationall.size(); i++) {
										if (id_check[i] != "") {
											count_isnull = count_isnull + 1;
											UpDateDataToServer report = new UpDateDataToServer();
											report.reportToBlueRoad(String
													.valueOf(informationall
															.get(i).id),
													returnMail(), "1");
											// show on google map
											show_report(
													Double.parseDouble(String
															.valueOf(informationall
																	.get(i).lat)),
													Double.parseDouble(String
															.valueOf(informationall
																	.get(i).lng)));

											Thread timer = new Thread() {
												public void run() {
													try {
														sleep(1000);
													} catch (InterruptedException e) {
														e.printStackTrace();
													}
												}
											};
											timer.start();
											// end wait update
										}
									}

									// show question when not choose
									if (count_isnull == 0) {
										chooseNull();
									} else {
										Toast.makeText(getBaseContext(),
												"Báo Cáo Thành Công",
												Toast.LENGTH_SHORT).show();
									}
									// end show question when not choose
									String show_current_point = "Điểm Chạm Tay Trên Bản Đồ";
									if (type_report == 0) {
										show_current_point = "Điểm Hiện Tại Của Bạn";
									}
									poinCurrent = googleMap
											.addMarker(new MarkerOptions()
													.position(POINT_CURRENT)
													.title(show_current_point)
													.draggable(true)
													.icon(BitmapDescriptorFactory
															.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
									Circle circle1 = googleMap
											.addCircle(new CircleOptions()
													.center(POINT_CURRENT)
													.radius(100)
													.strokeColor(Color.BLUE));
									circle1.setStrokeWidth(2);

									googleMap.moveCamera(CameraUpdateFactory
											.newLatLngZoom(POINT_CURRENT, 15));
									googleMap.animateCamera(
											CameraUpdateFactory.zoomTo(16),
											2000, null);

								}
							})
					.setNegativeButton("Hủy",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent menu = new Intent(Report.this, menu.class);
									startActivity(menu);
								}
							});
			builder.show();
		}

		// show dialog if not point
		public void findNull() {
			AlertDialog.Builder builder = new AlertDialog.Builder(Report.this);
			builder.setTitle("Lời Nhắn Từ Blue Road")
					.setMessage(
							"Chúng Tôi Không Tìm Thấy Điểm Có Khả Năng Xảy Ra Tắc Đường Trong Bán Kính 200 m ")
					.setPositiveButton("Quay Lại Sau",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Circle circle1 = googleMap
											.addCircle(new CircleOptions()
													.center(POINT_CURRENT)
													.radius(200)
													.strokeColor(Color.BLUE)
													.fillColor(0x40ff0000));
									circle1.setStrokeWidth(1);
								}
							})
					.setNegativeButton("Hủy",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent menu = new Intent(Report.this, menu.class);
									startActivity(menu);
									dialog.cancel();
								}
							}).setCancelable(false);
			builder.show();
		}

		// show dialog if choose null
		public void chooseNull() {
			AlertDialog.Builder builder = new AlertDialog.Builder(Report.this);
			builder.setMessage("Bạn Có Muốn Quay Lại Không?")
					.setTitle("  Bạn Chưa Chọn Điểm Nào  ")
					.setPositiveButton("Đồng Ý",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									reportDialog();
								}
							})
					.setNegativeButton("Hủy",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent menu = new Intent(Report.this, menu.class);
									startActivity(menu);
									dialog.cancel();
								}
							}).setCancelable(false);
			builder.show();
		}

		private int show_report(double lat, double lng) {
			if (lat != 0 && lng != 0) {
				POINT_SHOW = new LatLng(lat, lng);
				poinShow = googleMap
						.addMarker(new MarkerOptions()
								.position(POINT_SHOW)
								.title("Điểm Bạn Vừa Báo Cáo Tắc đường")
								.draggable(true)
								.icon(BitmapDescriptorFactory
										.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
				Circle circle1 = googleMap.addCircle(new CircleOptions()
						.center(POINT_SHOW).radius(100).strokeColor(Color.RED)
						.fillColor(0x40ff0000));
				circle1.setStrokeWidth(2);
				return 0;
			} else
				return 0;
		}
		
		public String returnMail() {
			Database getMail = new Database(Report.this);
			getMail.open();
			User mail_user = getMail.getData_USER();
			getMail.close();
			return mail_user.mail;
		}
	}
}
